package com.eportal.aop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.domain.Sysopt;
import com.eportal.domain.SystemLog;
import com.eportal.service.SystemLogService;
import com.eportal.service.impl.SysRolesTemplateServiceImpl;

import net.sf.json.JSONObject;  
  
  
/** 
 * @author pengjin 
 * @version 2.1 
 * @since 2.1 
 */  
public class WriteOperateLog {  

	@Autowired 
	private SystemLogService systemLogService;  
	private static Logger log = Logger.getLogger(WriteOperateLog.class.getName());
	
	public void writeLogInfo(JoinPoint joinPoint,Object returnValue) throws Exception,  
            IllegalAccessException {
       try {
		String temp = joinPoint.getStaticPart().toShortString();  
        String longTemp = joinPoint.getStaticPart().toLongString();  
        joinPoint.getStaticPart().toString();  
        String classType = joinPoint.getTarget().getClass().getName();  
        String methodName = temp.substring(10, temp.length() - 1);  
        methodName = methodName.substring(methodName.indexOf(".")+1,methodName.indexOf("("));//TODO wangk 2017-8-9 11:42:17 可能由于spring版本变更，之前的代码取值有问题，重新修改
        Class<?> className = Class.forName(classType);  
        // 日志动作  
        @SuppressWarnings("rawtypes")  
        Class[] args = new Class[joinPoint.getArgs().length];  
        /*String[] sArgs = longTemp.substring(longTemp.lastIndexOf("(") + 1,  
        		longTemp.lastIndexOf(")")).split(",");*/
      //TODO wangk 2017-8-9 11:42:17 可能由于spring版本变更，之前的代码取值有问题，重新修改
        String[] sArgs = longTemp.substring(longTemp.lastIndexOf("(") + 1,  
        		longTemp.lastIndexOf(")")-1).split(",");  
        for (int i = 0; i < args.length; i++) {  
            if (sArgs[i].endsWith("String[]")) {  
                args[i] = Array.newInstance(Class.forName("java.lang.String"),  
                        1).getClass();  
            } else if (sArgs[i].endsWith("Long[]")) {  
                args[i] = Array.newInstance(Class.forName("java.lang.Long"), 1)  
                        .getClass();  
            } else if (sArgs[i].indexOf(".") == -1) {  
                if (sArgs[i].equals("int")) {  
                    args[i] = int.class;  
                } else if (sArgs[i].equals("char")) {  
                    args[i] = char.class;  
                } else if (sArgs[i].equals("float")) {  
                    args[i] = float.class;  
                } else if (sArgs[i].equals("long")) {  
                    args[i] = long.class;  
                }  
            } else {  
                args[i] = Class.forName(sArgs[i]);  
            }  
        }  
        Method method = className.getMethod(methodName, args);  
        
        // 如果该方法写了注解才做操作  
        if (method.isAnnotationPresent(LogAnnotation.class)) {  
            LogAnnotation logAnnotation = method  
                    .getAnnotation(LogAnnotation.class);  
            HttpServletRequest request = ServletActionContext.getRequest();
            String operateDescribe = logAnnotation.operateDescribe(); 
            Sysopt  user= (Sysopt)request.getSession().getAttribute("user");
            request.getSession().removeAttribute("aopLogResult");
            request.getSession().removeAttribute("aopLogObjectId");
            SystemLog log = new SystemLog();
            if (returnValue != null) {
            	Map<String, Object> returnValueMap = (Map<String, Object>)returnValue;
            	log.setResult(returnValueMap.get("code").toString());
            	if (StringUtils.isNotBlank(returnValueMap.get("msg").toString())) {
            		log.setResultMsg(returnValueMap.get("msg").toString());
				}
            	
	            if (returnValueMap.get("objectId") != null) {
	            	log.setObjectId(returnValueMap.get("objectId").toString());
				}
			}
            log.setcTime(new Timestamp(System.currentTimeMillis()));
            log.setIpAdd(getIpAddr(request));	
            log.setOperObject(classType);
            log.setSlogComment(operateDescribe);
            log.setMethod(methodName);
            if(user != null){
            	log.setUserId(user.getSid());
            	log.setUsername(user.getUserName());
            }else{
            	log.setUsername("游客");
            }
            systemLogService.save(log);
        }
       } catch (Exception e) {
    	   log.error("操作日志记录异常",e);
			return;
		}
    }  
	public static String getIpAddr(HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
  
	public static void saveLog(String dir, String content) {
        try {
            File path = new File(dir);
            if (!path.exists()) {
                path.mkdir();
            }
            File LogDir = new File(path + "/"
                    + (Calendar.getInstance().get(Calendar.MONTH) + 1));
            if (!LogDir.exists()) {
                LogDir.mkdir();
            }
            File file = new File(LogDir + "/"
                    + Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
                    + ".log");
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedWriter br = new BufferedWriter(new FileWriter(file, true));
            br.write(content);
            br.newLine();
            br.flush();
            br.close();

            File LogDirOld = new File(
                    path
                            + "/"
                            + (Calendar.getInstance().get(Calendar.MONTH) - 2 > 0 ? (Calendar
                                    .getInstance().get(Calendar.MONTH) - 2)
                                    : Calendar.getInstance()
                                            .get(Calendar.MONTH) + 10));
            if (LogDirOld.exists()) {
                File[] fileOlds = LogDirOld.listFiles();
                for (File f : fileOlds) {
                    f.delete();
               }
               LogDirOld.delete();
           }
       } catch (Exception e) {
           e.printStackTrace();
           log.error("", e);
       }

   }
}  